﻿using MyLiEda.Events.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace MyLiEda.Events.Bus
{
    public class PassThroughEventBus : BaseEventBus
    {
        private readonly EventQueue eventQueue = new EventQueue();        
        private readonly IEventHandlerExecuteContext context;        

        public PassThroughEventBus(IEventHandlerExecuteContext context) :base(context)
        {
            this.context = context;            
            eventQueue.EventPushed += EventQueue_EventPushed;
        }

        private async void EventQueue_EventPushed(object sender, EventProcessedEventArgs e)
        => await this.context.HandleEventAsync(e.Event);

        public override Task PublishAsync<TEvent>(TEvent @event, CancellationToken cancellationToken = default)            
                => Task.Factory.StartNew(() => eventQueue.Push(@event));

        //public void Subscribe()
        //    => eventQueue.EventPushed += EventQueue_EventPushed;

        public override void Subscribe<TEvent, TEventHandler>() 
        {
            if (!this.context.HandlerRegistered<TEvent, TEventHandler>())
            {
                this.context.RegisterHandler<TEvent, TEventHandler>();
            }
        }


        #region IDisposable Support
        private bool disposedValue = false; // To detect redundant calls
        void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    this.eventQueue.EventPushed -= EventQueue_EventPushed;
                }

                disposedValue = true;
            }
        }
        public void Dispose() => Dispose(true);      

        
        #endregion





    }
}
